package com.sgkusbcamdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Parcelable;
import android.text.TextUtils;

import com.gkusbsdk.SZUSBSDK;
import com.qitianyong.selfclass.BaseActivityEvent;
import com.qitianyong.selfclass.GKDevice;
import com.qitianyong.selfclass.UsbDeviceFilter;

import de.greenrobot.event.EventBus;

import static com.qitianyong.selfclass.GKDevice.__hDevice;

public class UsbDetachedReceiver extends BroadcastReceiver {

    private UsbDevice device;
    private Context context;

    @Override
    public void onReceive(final Context context, Intent intent) {
        if (TextUtils.equals(intent.getAction(), UsbManager.ACTION_USB_DEVICE_DETACHED)) {
            boolean isGKUSBDevice = true;
            Parcelable parcelableExtra = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if (parcelableExtra instanceof UsbDevice) {
                device = (UsbDevice) parcelableExtra;
                try {
                    this.context = context;
                    isGKUSBDevice = UsbDeviceFilter.getMatchingHostDevice(this.context, R.xml.device_filter, device);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (isGKUSBDevice) {
                if ((GKDevice.__device == null)) {
                    if (__hDevice != 0) {
                        SZUSBSDK.GKUSB_Destroy(__hDevice);
                    }
                    __hDevice = 0;
                } else {
                    GKDevice.getInstance().releaseDevice();
                }
                 EventBus.getDefault().post(new BaseActivityEvent(BaseActivityEvent.DETACHUSB));
            }
        }
    }

}
